package controller;

import constant.Constant;
import entity.User;
import exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import service.GoldPointsService;
import util.AjaxResult;
import vo.GoldPointsVo;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/gp")
public class GoldPointsController {

    @Autowired
    GoldPointsService goldPointsService;

    //    显示剩余积分(金币)
    @RequestMapping("/findFrontSumByUid.do")
    @ResponseBody
    public AjaxResult findFrontSumByUid(HttpSession session) {
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        System.out.println("剩余积分user=" + user);
        GoldPointsVo goldPointsVo = new GoldPointsVo();
        if (null == user) {
            goldPointsVo.setSum_gold_count(0);
            goldPointsVo.setSum_point_count(0);
            return AjaxResult.isFail(goldPointsVo);
        }

        goldPointsVo = goldPointsService.findFrontSumByUid(user.getId());

        return AjaxResult.isOk(goldPointsVo);
    }

    //    提供积分兑换金币服务
    @RequestMapping("/conversionGold.do")
    public String conversionGold(Integer point_count, HttpSession session) {
        User user = (User) session.getAttribute(Constant.SESSION_USER);
        System.out.println(point_count + "金币兑换user=" + user);

        if (null == point_count || null == user) {
            //        重定向到兑换页面
            session.removeAttribute(Constant.Conversion_MESSAGE);
            return "redirect:/user/front_record.do";
        }

        try {
            if (goldPointsService.conversionGold(user.getId(), point_count)) {
//        兑换成功重定向到登录页面
                return "redirect:/user/loginFront.do";
            }
        } catch (ServiceException e) {
            System.out.println(e.getMessage());
            session.setAttribute(Constant.Conversion_MESSAGE, e.getMessage());
        }
//        兑换失败，回到原来页面
        return "redirect:/user/front_record.do";
    }
}
